
package com.ruhua.java.service;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ruhua.java.dao.SysConfig;
import com.ruhua.java.dao.User;
import com.ruhua.java.exception.ErrException;
import com.ruhua.java.repository.SysConfigRepository;
import com.ruhua.java.repository.UserRepository;
import com.ruhua.java.util.JwtToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.lang.reflect.Array;
import java.text.MessageFormat;
import java.util.*;

import static com.ruhua.java.util.CommonUtil.toJsonString;

@Service
public class WxAuthenticationService {

    @Autowired
    private ObjectMapper mapper;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private SysConfigRepository sysConfigRepository;

    @Value("${wx.code2session}")
    private String code2SessionUrl;

    private String appid="";
    private String appsecret="";

    public void setParam(){
        ArrayList<String> keys = new ArrayList<>();
        keys.add("wx_app_id");
        keys.add("wx_app_secret");
        List<SysConfig> list=sysConfigRepository.findByKeyIn(keys);
        list.forEach((e) -> {
            if(e.getKey().equals("wx_app_id")) {
                this.appid = e.getValue();
            }
            if(e.getKey().equals("wx_app_secret")) {
                this.appsecret = e.getValue();
            }
        });
    }


    public String code2Session(String code) {
        this.setParam();
        String url = MessageFormat.format(this.code2SessionUrl, this.appid, this.appsecret, code);
        RestTemplate rest = new RestTemplate(); Map<String, Object> session = new HashMap<>();
        String sessionText = rest.getForObject(url, String.class);

        try {
            session = mapper.readValue(sessionText, Map.class); } catch (JsonProcessingException e) {
            e.printStackTrace();
        }
        return this.registerUser(session);
    }


    private String registerUser(Map<String, Object> session) {
        String openid = (String)session.get("openid");
        if (openid == null){
            throw new ErrException("获取用户信息失败");
        }
        Optional<User> userOptional = this.userRepository.findByOpenid(openid);
if(userOptional.isPresent()){
            return JwtToken.makeToken(userOptional.get().getId());
        }
        User user = User.builder()
                .openid(openid)
                .build();
        userRepository.save(user);
        Long uid = user.getId();
        return JwtToken.makeToken(uid);
    }
}
